
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
#include <sstream>

#include "TraceFormatter.h"
#include "Helpers.h"


using namespace std;

TraceFormatter::TraceFormatter(string& s)
{
  _buff = TimeHeader(_buff);
  _buff += " - ";
  _buff.append(s);

}

TraceFormatter::~TraceFormatter(void)
{
}

//
// Shall be called once when the tracer is initialized
//
string& TraceFormatter::MakeTraceHeader(string& sin)
{
  _buff = sin;
  return sin;
}

//
// Shall be called at each paragraph
//
string& TraceFormatter::TimeHeader(string& sin)
{
  char h[30];
  // add header
  time_t now = time(0);
  tm* localtm = localtime(&now);

  strftime(h, sizeof(h), "%Y-%m-%d %H-%M-%S", localtm);
  sin = string(h);
  return sin;
}

string& TraceFormatter::GetFormatted()
{
  return _buff;
}

string& TraceFormatter::FormatBinToHex(const unsigned char* bin, const unsigned int size)
{
  vector<unsigned char> binVector ( &bin[0], &bin[size] );
  _buff += "\n\n";

  _buff+=HexFormat(binary_to_string(binVector));
  return _buff;
}

//
// 00 11 22 33 44 55 66 77   88 99 AA BB CC DD EE FF - zywxuvtr abcdefgh 
string HexFormat(string& is)
{
  const int maxLineItems = 32;
  unsigned int i = 0;
  ostringstream hex, oasc;
  istringstream iasc;  
  string tmp, out;  

  while( is.length() > 0){        
    if(is.length() > maxLineItems){
      tmp = is.substr(0,maxLineItems);    
      is = is.substr(maxLineItems, is.length() - maxLineItems);
    }
    else{
      string padStr(maxLineItems - is.length(), ' '); 
      tmp = is + padStr;
      is = "";
    }
    oasc.str("");
    hex.str("");
    i = 0;
    std::vector<unsigned char> asc_vec = string_to_binary(tmp);
    for (std::vector<unsigned char>::const_iterator it = asc_vec.begin(); it != asc_vec.end(); it++){      
      if(std::isprint(*it)){
        oasc << (*it);        
      }
      else{
        oasc << ".";
      }      
    }
    
    for(unsigned char n=0; n < tmp.length(); n=n+2){      
      hex << tmp.substr(n, 2) << " ";
      if(n == (maxLineItems/2)-2){      
        hex << " ";        
      }
    }

    out += hex.str() + " - " + oasc.str() + "\n";
  }
  
  return out;
}

//
